package at.irian.jsfatwork.service.impl;

import at.irian.jsfatwork.dao.OrderDao;
import at.irian.jsfatwork.dao.ProviderDao;
import at.irian.jsfatwork.domain.Dish;
import at.irian.jsfatwork.domain.Order;
import at.irian.jsfatwork.domain.OrderItem;
import at.irian.jsfatwork.domain.Provider;
import at.irian.jsfatwork.service.ProviderService;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Named("providerService")
@Singleton
public class ProviderServiceImpl implements ProviderService {
    @Inject
    private ProviderDao providerDao;
    @Inject
    private OrderDao orderDao;

    public Provider createNew() {
        return providerDao.createNew();
    }

    @Transactional
    public void save(Provider entity) {
        providerDao.persist(entity);
    }

    @Transactional
    public void delete(Provider provider) {
        Set<Order> orders = new HashSet<Order>();
        for (Dish dish : provider.getDishes()) {
            for (OrderItem item : dish.getOrderItems()) {
                orders.add(item.getOrder());
            }
        }
        for (Order order : orders) {
            order.setCustomer(null);
            orderDao.delete(order);
        }
        provider.getCategories().clear();
        providerDao.delete(provider);
    }

    @Transactional(readOnly = true)
    public Provider findById(long id) {
        return providerDao.findById(id);
    }

    @Transactional(readOnly = true)
    public List<Provider> findAll() {
        return providerDao.findAll();
    }

}
